package com.ygqh.baby.controller.admin;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.controller.utils.DocumentHandler;
import com.ygqh.baby.controller.utils.ExcelUtil;
import com.ygqh.baby.handler.SkuExcelHandler;
import com.ygqh.baby.model.SkuExcelModel;
import com.ygqh.baby.po.YgWholesalerPrebillRecord;
import com.ygqh.baby.po.YgWholesalerPrebillRecordDetail;
import com.ygqh.baby.po.YgWholesalerSku;
import com.ygqh.baby.service.FileService;
import com.ygqh.baby.service.YgWholesalerPrebillRecordDetailService;
import com.ygqh.baby.service.YgWholesalerPrebillRecordService;
import com.ygqh.baby.service.YgWholesalerSkuService;
import com.ygqh.baby.utils.JsonUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: sunshuo
 * @date: 2018/12/11 17:36
 */
@Controller
@RequestMapping("admin/wholesaleprebill")
public class WholesalerPrebillRecordController extends BaseController<YgWholesalerPrebillRecord, Long> {

	@Autowired
	private YgWholesalerPrebillRecordService ygWholesalerPrebillRecordService;
	@Autowired
	private YgWholesalerPrebillRecordDetailService ygWholesalerPrebillRecordDetailService;
	@Autowired
	private SkuExcelHandler skuExcelHandler;
	@Autowired
	private YgWholesalerSkuService ygWholesalerSkuService;
	@Autowired
	private FileService fileService;

	/**
	 * 查询预结单
	 *
	 * @param queryInfo
	 * @param wholesalerName
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@RequestMapping("searchPrebillRecord")
	@ResponseBody
	public Map<String, Object> searchPrebillRecord(QueryInfo queryInfo, String wholesalerName, Date startDate, Date endDate, String billCode, String prebillCode,
												   CommitStatus commitStatus) {
		ResultSet<YgWholesalerPrebillRecord> resultSet = ygWholesalerPrebillRecordService.search(queryInfo, wholesalerName, startDate, endDate, billCode, prebillCode,
				commitStatus);
		return resultSet.toDatatables(null);
	}

	/**
	 * 编辑预结单
	 *
	 * @param record
	 * @return
	 */
	@RequestMapping("editPrebillRecord")
	@ResponseBody
	public Message editPrebillRecord(YgWholesalerPrebillRecord record) {
		record.setUpdateBy(getSession().getTrueName());
		record.setUpdateTime(new Date());
		ygWholesalerPrebillRecordService.editPrebillRecord(record);
		return Message.success(null);
	}

	/**
	 * 查询预结单明细
	 *
	 * @param queryInfo
	 * @param wholesalerName
	 * @param detailCode
	 * @param prebillCode
	 * @param startDate
	 * @param endDate
	 * @param recordType
	 * @return
	 */
	@RequestMapping("searchDetail")
	@ResponseBody
	public Map<String, Object> searchDetail(QueryInfo queryInfo, String wholesalerName, String detailCode, String prebillCode,
											Date startDate, Date endDate, @RequestParam WholeSaleRecordType recordType) {
		ResultSet<YgWholesalerPrebillRecordDetail> resultSet = ygWholesalerPrebillRecordDetailService
				.searchDetail(queryInfo, wholesalerName, detailCode, prebillCode, startDate, endDate, recordType);
		return resultSet.toDatatables(null);
	}

	/**
	 * 加载导入的SKU数量数据
	 *
	 * @param uploadFile
	 * @return
	 */
	@RequestMapping(value = "loadExcelByReturnOrder", method = RequestMethod.POST)
	@ResponseBody
	public Message loadExcelByWholesale(@RequestParam("uploadFile") MultipartFile uploadFile, @RequestParam("wholesalerId") Long wholesalerId) {
		List<Map<Integer, Object>> excelInfo;
		try {
			excelInfo = ExcelUtil.readExcel(uploadFile);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return Message.error("读取导入数据错误", null);
		}
		List<SkuExcelModel> modelList = skuExcelHandler.handlerExcelInfo(excelInfo, SkuExcelModel.SkuExcelType.SkuQuantity);
		if (CollectionUtils.isEmpty(modelList)) {
			return Message.error("导入的数据解析为空", null);
		}
		List<String> skuCodeList = modelList.stream().map(SkuExcelModel::getSkuCode).collect(Collectors.toList());
		List<YgWholesalerSku> wholesalerSkuList = ygWholesalerSkuService.findBySkuCode(skuCodeList, wholesalerId);
		Map<String, List<YgWholesalerSku>> collect = wholesalerSkuList.stream().collect(Collectors.groupingBy(YgWholesalerSku::getSkuCode));
		modelList.forEach(model -> {
			if (StringUtils.isNotBlank(model.getErrMsg())) {
				return;
			}
			if (collect.containsKey(model.getSkuCode())) {
				model.setPrice(collect.get(model.getSkuCode()).get(0).getWholesalePrice());
			} else {
				model.setErrMsg("SKU批发价未设置");
			}
		});
		return Message.success(modelList);
	}

	/**
	 * 保存退货明细
	 *
	 * @param wholesalerId
	 * @param prebillRecordDetails
	 * @return
	 */
	@RequestMapping("saveReturnOrderDetail")
	@ResponseBody
	public Message saveReturnOrderDetail(@RequestParam Long wholesalerId, @RequestParam String prebillRecordDetails) {
		List<YgWholesalerPrebillRecordDetail> list = JsonUtils.toObject(prebillRecordDetails, new TypeReference<List<YgWholesalerPrebillRecordDetail>>() {
		});
		ygWholesalerPrebillRecordService.saveReturnOrder(wholesalerId, list, getSession().getTrueName());
		return Message.success(null);
	}

	/**
	 * 导出指定预结单明细
	 *
	 * @param prebillCode
	 * @param request
	 * @param response
	 */
	@RequestMapping("exportRecordDetail")
	public void exportRecordDetail(@RequestParam String prebillCode, HttpServletRequest request, HttpServletResponse response) {
		List<YgWholesalerPrebillRecordDetail> list = ygWholesalerPrebillRecordDetailService.findByPrebillCode(prebillCode);
		byte[] bytes = fileService.downloadFromOss(FileTemplate.WholesalerPrebillRecord.getCode());
		Map<String, Object> dataMap = new HashMap<>(1);
		dataMap.put("resultSet", list);
		DocumentHandler.DownloadExcel(bytes, prebillCode + FileTemplate.WholesalerPrebillRecord.getTitle(), dataMap, request, response);
	}
}
